package com.haierp.controller.youzan;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.haierp.enums.OrderStatus;
import com.haierp.enums.PayType;
import com.haierp.enums.PlatformType;
import com.haierp.exception.InventoryException;
import com.haierp.mapper.OuterOrderDetailMapper;
import com.haierp.mapper.OuterOrderMapper;
import com.haierp.model.ErpOrder;
import com.haierp.model.Inventory;
import com.haierp.model.ItemSku;
import com.haierp.model.sale.OuterOrder;
import com.haierp.model.sale.OuterOrderDetail;
import com.haierp.model.youzan.YouzanTradeGet;
import com.haierp.model.youzan.YouzanTradeGetResult;
import com.haierp.model.youzan.YouzanTradeGetResult.StructurizationTradeItemDetail;
import com.haierp.model.youzan.YouzanTradeGetResult.StructurizationTradeOrderInfo;
import com.haierp.service.IErpOrderService;
import com.haierp.service.IInventoryService;
import com.haierp.service.IItemSkuService;
import com.haierp.service.IOuterOrderService;
import com.haierp.service.ISequenceUtilService;
import com.haierp.service.youzan.IYouzanService;
import com.haierp.util.DateUtil;
import com.haierp.util.DimensionCodeUtil;
import com.wangzhixuan.commons.base.BaseController;
import com.youzan.open.sdk.client.auth.Token;
import com.youzan.open.sdk.client.core.DefaultYZClient;
import com.youzan.open.sdk.gen.v3_0_0.model.YouzanTradeGetParams;
import com.youzan.open.sdk.util.json.JsonUtils;

import net.sf.json.JSONObject;

/**
 * YouzanPushMessageController 推送服务消息接收示例 依赖SPRING 3.0或以上版本
 * 
 * @auther ChengZi
 * @data 16/9/10
 */
@Controller
@RequestMapping("/youzanPushMessage")
public class YouzanPushMessageController extends BaseController {

	@Autowired
	private ISequenceUtilService sequenceUtilService;

	@Autowired
	private OuterOrderMapper outerOrderMapper;

	@Autowired
	private OuterOrderDetailMapper outerOrderDetailMapper;

	@Autowired
	private IInventoryService inventoryService;

	@Autowired
	private IItemSkuService itemSkuService;

	@Autowired
	private IOuterOrderService outerOrderService;

	@Autowired
	private IErpOrderService erpOrderService;

	@Autowired
	private IYouzanService youzanService;

	private static final int mode = 1; // 服务商
	private DefaultYZClient yzClient = new DefaultYZClient(new Token(DimensionCodeUtil.youZanToken));

	@RequestMapping(value = "/pullOrder", method = RequestMethod.POST)
	@ResponseBody
	public Object pullOrder(HttpServletRequest request) {
		// logger.error("推送消息：" + entity.toString());
		//System.out.println("进来了");
		JSONObject res = new JSONObject();
		res.put("code", 0);
		res.put("msg", "success");

		InputStream in;
		try {
			in = request.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String jsonStr = br.readLine();
			System.out.println(jsonStr);
			JSONObject param = JSONObject.fromObject(jsonStr);
			//String targetNo = param.getString("id");
			String msg = param.getString("msg");
			String msgType = param.getString("type");
			String truemsg = URLDecoder.decode(msg, "utf-8");
			System.out.println(truemsg);
			String pullTid = null;
			JSONObject myJson = JSONObject.fromObject(truemsg);
			if ("trade_TradeClose".equals(msgType)) {
				pullTid = myJson.getString("tid");
			} else {
				JSONObject full_order_info = myJson.getJSONObject("full_order_info");
				JSONObject order_info = full_order_info.getJSONObject("order_info");
				//String status = order_info.getString("status");
				pullTid = order_info.getString("tid");
			}
			logger.error("有赞推送明细V3===>" + msgType);
			if ("trade_TradeCreate".equals(msgType) || "trade_TradeBuyerPay".equals(msgType)
					|| "trade_TradeClose".equals(msgType)) {
				// 方法
				YouzanTradeGet youzanTradeGet = new YouzanTradeGet();
				// 参数
				YouzanTradeGetParams youzanTradeGetParams = new YouzanTradeGetParams();
				// 买家已付款，等待发货
				youzanTradeGetParams.setTid(pullTid);
				List<Long> outOrderIdList = new ArrayList<Long>();
				youzanTradeGet.setAPIParams(youzanTradeGetParams);

				YouzanTradeGetResult result = yzClient.invoke(youzanTradeGet);
				logger.error("有赞拉取明细V4===>" + JsonUtils.toJson(result));
				StructurizationTradeOrderInfo fullOrderInfo = result.getFullOrderInfo();
				// 如果有赞订单已存在，略过
				OuterOrder p = new OuterOrder();
				p.setTargetNo(fullOrderInfo.getOrderInfo().getTid());
				if (outerOrderMapper.selectCount(p) > 0) {
					if ("trade_TradeBuyerPay".equals(msgType)) { //已支付
						OuterOrder outerOrder = outerOrderMapper.selectOne(p);
						outerOrder.setStatus(OrderStatus.INIT.getCode());
						outerOrder.setOrderTime(fullOrderInfo.getOrderInfo().getPayTime());
						outerOrder.setGmtModify(fullOrderInfo.getOrderInfo().getUpdateTime());
						outerOrderMapper.updateSelectiveById(outerOrder);
					}
					if ("trade_TradeClose".equals(msgType)) { //交易关闭
						// logger.error("进来了5"+ msgDetail.getStatus());
						OuterOrder outerOrder = outerOrderMapper.selectOne(p);
						// 1、释放子订单库存
						EntityWrapper<ErpOrder> entityWrapper = new EntityWrapper<>();
						entityWrapper.where("outer_order_id = {0} ", outerOrder.getId());
						List<ErpOrder> erpOrders = erpOrderService.selectList(entityWrapper);
						if (CollectionUtils.isNotEmpty(erpOrders)) {
							for (ErpOrder erpOrder : erpOrders) {
								try {
									// 1,释放子订单库存
									inventoryService.releaseInventory(erpOrder);
									// 2,更改子订单状态
									erpOrder.setStatus(OrderStatus.CLOSE.getCode());
									erpOrder.setGmtModify(new Date());
									erpOrderService.updateById(erpOrder);
								} catch (InventoryException e) {
									e.printStackTrace();
								}
							}
						}
						// 2、更改主子订单状态
						outerOrder.setStatus(OrderStatus.CLOSE.getCode());
						outerOrder.setGmtModify(new Date());
						outerOrderService.updateById(outerOrder);
					}
				} else {
					// 如果有赞订单还不存在，继续
					OuterOrder outerOrder = new OuterOrder();
					// 有赞平台为01,销售为0000
					outerOrder.setOrderNo("P" + String.format("%0" + 2 + "d", 1) + String.format("%0" + 4 + "d", 4) + "D"
							+ DateUtil.formatDate(fullOrderInfo.getOrderInfo().getCreated(), DateUtil.DATE_PARTEN_YYMMDDHHMMSS)
							+ sequenceUtilService.gainORDSequence()); // 系统自动生成
					if (fullOrderInfo.getOrderInfo().getPayTime() == null) {
						outerOrder.setOrderTime(new Date());
					} else {
						outerOrder.setOrderTime(fullOrderInfo.getOrderInfo().getPayTime());
					}
					if ("trade_TradeBuyerPay".equals(msgType)) {
						outerOrder.setStatus(OrderStatus.INIT.getCode()); // 新建(已付款)
					} else if ("trade_TradeCreate".equals(msgType)) {
						outerOrder.setStatus(OrderStatus.WAITBUYERPAY.getCode()); // 待付款
					}
					outerOrder.setReceiver(fullOrderInfo.getAddressInfo().getReceiverName()); // 收货人
					outerOrder.setReceiverState(fullOrderInfo.getAddressInfo().getDeliveryProvince()); // 省
					outerOrder.setReceiverCity(fullOrderInfo.getAddressInfo().getDeliveryCity()); // 市
					outerOrder.setReceiverDistrict(fullOrderInfo.getAddressInfo().getDeliveryDistrict()); // 区
					outerOrder.setAddressDetail(fullOrderInfo.getAddressInfo().getDeliveryAddress()); // 详细地址
					outerOrder.setTelephone(fullOrderInfo.getAddressInfo().getReceiverTel()); // 联系电话
					outerOrder.setPostcode(fullOrderInfo.getAddressInfo().getDeliveryPostalCode()); // 邮编
					outerOrder.setRemark(fullOrderInfo.getRemarkInfo().getBuyerMessage()); // 买家购买附言
					outerOrder.setTargetNo(fullOrderInfo.getOrderInfo().getTid()); // 有赞平台交易编号
					outerOrder.setIdCard(fullOrderInfo.getOrderInfo().getOrderExtra().getIdCardNumber()); // 身份证
					outerOrder.setPlatformType(PlatformType.YOUZAN.getCode()); // 销售来源(平台)
					if (StringUtil.isNotBlank(fullOrderInfo.getOrderInfo().getPayTypeStr())) {
						outerOrder.setPayType(PayType.valueOf(fullOrderInfo.getOrderInfo().getPayTypeStr()).getCode()); // 支付方式
					}
					outerOrder.setUserCreate("有赞推送订单"); // 创建者
					outerOrder.setUserModify("有赞推送订单"); // 修改者
					outerOrder.setGmtCreate(fullOrderInfo.getOrderInfo().getCreated()); // 创建时间
					outerOrder.setGmtModify(fullOrderInfo.getOrderInfo().getUpdateTime()); // 修改时间
					outerOrder.setSalesName("有赞");
					outerOrder.setSalesId(4L);
					outerOrder.setCompanyId(1L); // 订单所属公司
					outerOrderMapper.insert(outerOrder); // 添加主订单

					outOrderIdList.add(outerOrder.getId()); // 收集主订单ID

					StructurizationTradeItemDetail[] ordersDetailArr = fullOrderInfo.getOrders();
					List<OuterOrderDetail> outerOrderDetails = new ArrayList<OuterOrderDetail>();
					String ConsigneeIDFrontUrl = null;	//身份证正面url
					String ConsigneeIDBackUrl = null;	//身份证反面url
					for (int j = 0; j < ordersDetailArr.length; j++) {
						StructurizationTradeItemDetail ordersDetail = ordersDetailArr[j];

						OuterOrderDetail outerOrderDetail = new OuterOrderDetail();
						outerOrderDetail.setOuterOrderId(outerOrder.getId()); // 主订单ID
						outerOrderDetail.setSkuCode(ordersDetail.getOuterSkuId()); // sku编码
						outerOrderDetail.setSalePrice(Double.parseDouble(String.valueOf(ordersDetail.getPrice()))); // 商品单价
						outerOrderDetail.setQuantity(Integer.parseInt(String.valueOf(ordersDetail.getNum()))); // 购买数量
						outerOrderDetail.setOid(String.valueOf(ordersDetail.getOid())); // 商品交易明细编号
						outerOrderDetail.setGmtCreate(fullOrderInfo.getOrderInfo().getCreated()); // 创建时间
						outerOrderDetail.setGmtModify(fullOrderInfo.getOrderInfo().getUpdateTime()); // 修改时间
						outerOrderDetail.setCompanyId(1L); // 订单明细所属公司
						outerOrderDetails.add(outerOrderDetail);

						if(StringUtil.isNotBlank(ordersDetail.getBuyerMessages()) && StringUtil.isBlank(ConsigneeIDFrontUrl)) {
							JSONObject  jasonObject = JSONObject.fromObject(ordersDetail.getBuyerMessages());
							Map map = (Map)jasonObject;
							ConsigneeIDFrontUrl = (String)map.get("身份证正面");
							ConsigneeIDBackUrl = (String)map.get("身份证反面");
							if(StringUtil.isNotBlank(ConsigneeIDFrontUrl)) {
								ConsigneeIDFrontUrl = youzanService.getAliyunImageUrl(ConsigneeIDFrontUrl);
							}
							if(StringUtil.isNotBlank(ConsigneeIDBackUrl)) {
								ConsigneeIDBackUrl = youzanService.getAliyunImageUrl(ConsigneeIDBackUrl);
							}
						}

						// 如果有虚拟库存就扣减虚拟库存
						ItemSku tjItemSku = new ItemSku();
						tjItemSku.setSkuCode(ordersDetail.getOuterSkuId());
						ItemSku itemSku = itemSkuService.selectOne(tjItemSku);
						if (itemSku != null) {
							Inventory inventory = inventoryService.queryInventoryBySkuId(itemSku.getItemId(),
									itemSku.getId());
							if (inventory.getVirtualInv() > 0) {
								int virtualInv = inventory.getVirtualInv() - outerOrderDetail.getQuantity();
								virtualInv = virtualInv > 0 ? virtualInv : 0;
								// 如果虚拟库存小于等于可售库存，虚拟库存清零
								virtualInv = virtualInv > inventory.getTotalAvailableInv() ? virtualInv : 0;

								// 如果虚拟占用库存大于零，有赞下单不应该减少虚拟预扣
								/*
								 * if(inventory.getLockedVirtualInv() > 0) { int
								 * lockedVirtualInv =
								 * inventory.getLockedVirtualInv() -
								 * outerOrderDetail.getQuantity(); lockedVirtualInv
								 * = lockedVirtualInv>0 ? lockedVirtualInv : 0;
								 * inventory.setLockedVirtualInv(lockedVirtualInv);
								 * }
								 */
								inventory.setVirtualInv(virtualInv);
								inventory.setGmtModify(new Date());
								inventoryService.updateSelectiveById(inventory);
							}
						}
					}
					outerOrderDetailMapper.insertBatch(outerOrderDetails); // 添加子订单

					if(StringUtil.isNotBlank(ConsigneeIDFrontUrl) && StringUtil.isNotBlank(ConsigneeIDBackUrl)) {
						outerOrder.setIdcardPicFront(ConsigneeIDFrontUrl);
						outerOrder.setIdcardPicReverse(ConsigneeIDBackUrl);
						outerOrderMapper.updateSelectiveById(outerOrder);
					}

					if (outOrderIdList.size() > 0) {
						// 把商品详情更新到主订单明细里面
						outerOrderDetailMapper.updateOuterOrderDetailByItemSku(outOrderIdList);
						// 生成子订单并配货
						outOrderIdList.forEach(erpOrderId -> {
							outerOrderService.review(erpOrderId, "YZ");
						});
					}
				}
			}
		} catch (IOException e1) {
			e1.printStackTrace();
			this.logger.error("读取流异常" + e1);
		}
		return res;

	}
}
